package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.prefix}")
    private String prefix; //oss上资源存储的顶层目录

    @Value("${file.oss.web-site}")
    private String webSite; //访问oos的域名

    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查上传的文件是否为空
        if (multipartFile == null || multipartFile.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.检查当前用户是否已登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.执行上传文件到OSS上
        String fileUrl = "";
        try {

            //处理上传文件的文件名
            //处理文件名前缀，保证文件名是唯一的
            String filePrefix = UUID.randomUUID().toString().replace("-", "");

            //获取上传的文件的原始文件名 xxxxx.png
            String fileOrgName = multipartFile.getOriginalFilename();

            int index = fileOrgName.lastIndexOf("."); //得到最后一个.的索引位置
            String filePostfix = fileOrgName.substring(index); //文件名后缀

            //前缀 后缀拼接
            String fullName = filePrefix + filePostfix;

            //上传之后响应的fileUrl的值格式：/material/a/b/d/11.png
            fileUrl = fileStorageService.store(prefix, fullName, multipartFile.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "上传出现问题");
        }

        //4.将素材数据保存到素材表
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(fileUrl);
        wmMaterial.setType((short) 0); // 0:图片 ， 1：视频
        wmMaterial.setIsCollection((short) 0); //0:未收藏  ， 1：已收藏
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //5.响应数据，图片回显
        wmMaterial.setUrl(webSite + fileUrl);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.检查参数
        if (dto == null || dto.getIsCollection() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2.判断用户是否已登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.查询当前用户的素材列表
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper();
        wrapper.eq(WmMaterial::getUserId, user.getId());

        //4.判断收藏字段是否有值，如果Collection>0 拼接条件查询
        if (dto.getIsCollection() > 0) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        //5.素材列表应该根据时间倒排
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        //设置分页
        IPage<WmMaterial> iPage = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> page = page(iPage, wrapper);

        //6.响应数据，并让图片数据能在页面显示
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        List<WmMaterial> records = page.getRecords();
        //遍历,拼接域名
        for (WmMaterial wmMaterial : records) {
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        }
        responseResult.setData(records);

        return responseResult;
    }

    /**
     * 素材删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {
        //1.检查参数
        if (id == null || id == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否已登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "素材不存在");
        }

        //3.判断数据是否存在
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //4.查看素材是否被关联 ,wm_news_material 素材与文章的关联
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);

        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "素材被关联无法删除");
        }

        //5.执行删除
        removeById(id);

        //6.删除阿里云的文件
        fileStorageService.delete(wmMaterial.getUrl());

        //7.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏 取消收藏
     *
     * @param id
     * @param isCollect
     * @return
     */
    @Override
    public ResponseResult collect(Integer id, Short isCollect) {
        //1.检查参数
        if (id == null || id == 0 || isCollect == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否已登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.判断数据是否存在
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //4.执行更新
        WmMaterial wmMaterial1 = new WmMaterial();
        wmMaterial1.setId(id);
        wmMaterial1.setIsCollection(isCollect);
        updateById(wmMaterial1);

        // 方式二: LambdaUpdateWrapper
        //LambdaUpdateWrapper<WmMaterial> wrapper = new LambdaUpdateWrapper<>();
        //wrapper.eq(WmMaterial::getId, id);
        //wrapper.eq(WmMaterial::getUserId, user.getId());
        //wrapper.set(WmMaterial::getIsCollection, isCollect);
        //update(wrapper);

        //5.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
